<template>
	<view>
		<!--pages/submit-order/submit-order.wxml-->
		<view class="container">
			<view class="submit-order">
				<!-- 收货地址 -->
				<view class="delivery-addr " @tap="toAddrListPage">
					<!-- <view class="addr-bg " v-if="!userAddr">
						<view class="add-addr">
							<view class="plus-sign-img">
								<image src="../../static/images/icon/plus-sign.png"></image>
							</view>
							<text>新增收货地址</text>
						</view>
						<view class="arrow empty"></view>
					</view> -->
					<view class="addr-bg whole" v-if="userAddr">
						<view class="addr-icon">
							<image src="../../static/images/icon/addr.png"></image>
						</view>
						<view class="user-info">
							<text class="item">{{userAddr.receiver}}</text>
							<text class="item">{{userAddr.mobile}}</text>
						</view>
						<view class="addr">{{userAddr.province}}{{userAddr.city}}{{userAddr.area}}{{userAddr.addr}}
						</view>
						<view class="arrow"></view>
					</view>
				</view>

				<!-- 商品详情 -->
				<view class="prod-item">
					<block v-for="(item, index) in orderItems" :key="index">
						<view class="item-cont" @tap="toOrderDetailPage" :data-ordernum="item.primaryOrderNo">
							<view class="prod-pic">
								<image :src="item.pic"></image>
							</view>
							<view class="prod-info">
								<view class="prodname">
									{{item.prodName}}
								</view>
								<view class="prod-info-cont">{{item.skuName}}</view>
								<view class="price-nums">
									<text class="prodprice"><text class="symbol">￥</text>
										<text class="big-num">{{wxs.parsePrice(item.price)[0]}}</text>
										<text class="small-num">.{{wxs.parsePrice(item.price)[1]}}</text></text>
									<text class="prodcount">x{{item.prodCount}}</text>
								</view>
							</view>
						</view>
					</block>
					<!-- <view class='item-cont' bindtap='toOrderDetailPage' data-ordernum="{{item.primaryOrderNo}}">
        <view class='prod-pic'>
          <image src='../../images/prod/pic09.jpg'></image>
        </view>
        <view class='prod-info'>
          <view class='prodname'>
            THE BEAST/野兽派 易烊千玺同款
          </view>
          <view class='prod-info-cont'>经典杯型升级，杯型更细长优雅</view>
          <view class='price-nums'>
            <text class='prodprice'><text class='symbol'>￥</text>
            <text class='big-num'>{{wxs.parsePrice(40.00)[0]}}</text>
            <text class='small-num'>.{{wxs.parsePrice(40.00)[1]}}</text></text>
            <text class="prodcount">x1</text>
          </view>
        </view>
      </view> -->

					<view class="total-num">
						<text class="prodcount">共{{totalCount}}件商品</text>
						<view class="prodprice">合计：
							<text class="symbol">￥</text>
							<text class="big-num">{{wxs.parsePrice(total)[0]}}</text>
							<text class="small-num">.{{wxs.parsePrice(total)[1]}}</text>
						</view>
					</view>
				</view>

				<!-- 订单详情 -->
				<view class="order-msg">
					<view class="msg-item">
						<view class="item coupon" @tap="showCouponPopup">
							<text class="item-tit">优惠券：</text>
							<text class="item-txt" v-if="!coupons.canUseCoupons">暂无可用</text>
							<text class="coupon-btn">{{coupons.totalLength? coupons.totalLength: 0}}张</text>
							<text class="arrow"></text>
						</view>
						<view class="item">
							<text>买家留言：</text>
							<input v-model="remarks" placeholder="给卖家留言"></input>
						</view>
					</view>

				</view>

				<view class="order-msg">
					<view class="msg-item">
						<view class="item">
							<view class="item-tit">订单总额：</view>
							<view class="item-txt price">
								<text class="symbol">￥</text>
								<text class="big-num">{{wxs.parsePrice(total)[0]}}</text>
								<text class="small-num">.{{wxs.parsePrice(total)[1]}}</text>
							</view>
						</view>
						<view class="item">
							<view class="item-tit">运费：</view>
							<view class="item-txt price">
								<text class="symbol">￥</text>
								<text class="big-num">{{wxs.parsePrice(transfee)[0]}}</text>
								<text class="small-num">.{{wxs.parsePrice(transfee)[1]}}</text>
							</view>
						</view>
						<view class="item">
							<view class="item-tit">优惠金额：</view>
							<view class="item-txt price">
								<text class="symbol">-￥</text>
								<text class="big-num">{{wxs.parsePrice(shopReduce)[0]}}</text>
								<text class="small-num">.{{wxs.parsePrice(shopReduce)[1]}}</text>
							</view>
						</view>
						<view class="item payment">
							<view class="item-txt price">
								小计：
								<text class="symbol">￥</text>
								<text class="big-num">{{wxs.parsePrice(actualTotal)[0]}}</text>
								<text class="small-num">.{{wxs.parsePrice(actualTotal)[1]}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="pay-select" v-if=" 'video' === from">
					<view class="pay-title">选择支付方式</view>
					<view class="pay-item borderbottom" @click="onCheck(0,1)">
						<image src="/static/img/wx.png" mode="aspectFit"></image>
						<view class="pay-name">微信</view>
						<checkbox :checked="0==currentIndex" />
					</view>
					<view class="pay-item" @click="onCheck(1,2)">
						<image src="/static/img/ali.png" mode="aspectFit"></image>
						<view class="pay-name">支付宝</view>
						<checkbox :checked="1==currentIndex" />
					</view>
				</view>
			</view>


			<!-- 底部栏 -->
			<view class="submit-order-footer">
				<view class="sub-order">
					<view class="item-txt">
						合计：
						<view class="price">
							<text class="symbol">￥</text>
							<text class="big-num">{{wxs.parsePrice(actualTotal)[0]}}</text>
							<text class="small-num">.{{wxs.parsePrice(actualTotal)[1]}}</text>
						</view>
					</view>
				</view>
				<view class="footer-box" @tap="toPay">
					提交订单
				</view>
			</view>
		</view>

		<uni-popup type="bottom" ref="popup" background-color="#fff">
			<view class="pop-wrap">
				<input type="text" password v-model="securityCode" placeholder="请输入安全密码" />
				<button type="default" @click="securityCodeConfirm">确定</button>
			</view>
		</uni-popup>

		<!-- 选择优惠券弹窗 -->
		<view class="popup-hide" v-if="popupShow">
			<view class="popup-box">
				<view class="popup-tit">
					<text>优惠券</text>
					<text class="close" @tap="closePopup"></text>
				</view>
				<view class="coupon-tabs">
					<view :class="'coupon-tab ' + (couponSts==1?'on':'')" @tap="changeCouponSts" data-sts="1">
						可用优惠券({{coupons.canUseCoupons.length?coupons.canUseCoupons.length:0}})</view>
					<view :class="'coupon-tab ' + (couponSts==2?'on':'')" @tap="changeCouponSts" data-sts="2">
						不可用优惠券({{coupons.unCanUseCoupons.length?coupons.unCanUseCoupons.length:0}})</view>
				</view>
				<view class="popup-cnt">
					<block v-for="(item, index) in coupons.canUseCoupons" :key="index" v-if="couponSts == 1">
						<coupon :item="item" order="true" @checkCoupon="checkCoupon" canUse="true"></coupon>
					</block>
					<block v-for="(item, index) in coupons.unCanUseCoupons" :key="index" v-if="couponSts == 2">
						<coupon :item="item" order="true" canUse="false"></coupon>
					</block>
					<view class="botm-empty"></view>
				</view>
				<view class="coupon-ok" v-if="couponSts==1">
					<text @tap="choosedCoupon">确定</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.js"></script>

<script>
	// pages/submit-order/submit-order.js
	var http = require("../../utils/http.js");
	import coupon from "../../components/coupon/coupon";
	import config from '../../../common/config.js'


	export default {
		data() {
			return {
				popupShow: false,
				couponSts: 1,
				couponList: [],
				// 订单入口 0购物车 1立即购买
				orderEntry: "0",
				userAddr: null,
				orderItems: [],
				coupon: {
					totalLength: 0,
					canUseCoupons: [],
					noCanUseCoupons: []
				},
				actualTotal: 0,
				total: 0,
				totalCount: 0,
				transfee: 0,
				reduceAmount: 0,
				remarks: "",
				couponIds: [],
				coupons: {},
				shopReduce: "",
				item: {},
				selAddress: '',

				userId: '',
				inviter: '',
				hasPassword: false, //是否设置了安全密码
				securityCode: '', //安全密码
				isMember: false, //是否购买小会员
				diskAddress: '', //网盘
				diskCode: '', //网盘
				belongId: '',
				from: '',
				currentIndex: 0, //支付方式
				payType: 1, // 1微信 2支付宝
			};
		},

		components: {
			coupon
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			console.log('订单页面参数：', options)
			this.userId = uni.getStorageSync('userid')
			this.setData({
				orderEntry: options.orderEntry
			});
			this.from = options.from
			this.belongId = options.belongId

			console.log('from:', this.from)
			console.log('belongId:', this.belongId)
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			uni.$off('submit')
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			var pages = getCurrentPages();
			var currPage = pages[pages.length - 1];
			console.log('currPage:', currPage.selAddress)
			if (currPage.selAddress == "yes") {
				//将携带的参数赋值
				this.userAddr = currPage.item
			}

			//获取订单数据
			this.loadOrderData();
			this.checkPassword()
			this.getInviter()
			uni.$on('submit', res => {
				console.log('接收事件：', res);
				this.hasPassword = true
			})

		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			uni.$off('submit')
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			// 查询是否有提现密码
			checkPassword() {
				console.log('userid:' + this.userId)
				uni.request({
					url: config.mallHost + '/p/user/getSecurityCode/' + this.userId,
					method: 'GET',
					header: {
						"Content-Type": "application/json", //自定义请求头信息
					},
					success: (res) => {
						console.log('提现密码：', res)
						if (res.statusCode == 200) {
							this.hasPassword = true
						} else {
							this.hasPassword = false
						}
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			getInviter() {
				this.inviter = uni.getStorageSync('inviter')
				console.log('inviter:', this.inviter)
			},

			//加载订单数据
			loadOrderData: function() {
				var addrId = 0;
				console.log('加载订单数据 addr: ', this.userAddr)

				if (this.userAddr != null) {
					addrId = this.userAddr.addrId;
				}

				uni.showLoading({
					mask: true
				});
				let datas = {
					addrId: addrId,
					orderItem: this.orderEntry === "1" ? JSON.parse(uni.getStorageSync("orderItem")) : undefined,
					basketIds: this.orderEntry === "0" ? JSON.parse(uni.getStorageSync("basketIds")) : undefined,
					couponIds: this.couponIds,
					userChangeCoupon: 1
				}
				console.log('订单参数：', datas)
				var params = {
					url: "/p/order/confirm",
					method: "POST",
					data: {
						addrId: addrId,
						orderItem: this.orderEntry === "1" ? JSON.parse(uni.getStorageSync("orderItem")) :
							undefined,
						basketIds: this.orderEntry === "0" ? JSON.parse(uni.getStorageSync("basketIds")) :
							undefined,
						couponIds: this.couponIds,
						userChangeCoupon: 1
					},
					callBack: res => {
						uni.hideLoading();
						let orderItems = [];
						res.shopCartOrders[0].shopCartItemDiscounts.forEach(itemDiscount => {
							orderItems = orderItems.concat(itemDiscount.shopCartItems);
						});
						if (orderItems.length === 1 && orderItems[0].prodName === '小会员') {
							this.isMember = true
						}
						if (res.shopCartOrders[0].coupons) {
							let canUseCoupons = [];
							let unCanUseCoupons = [];
							res.shopCartOrders[0].coupons.forEach(coupon => {
								if (coupon.canUse) {
									canUseCoupons.push(coupon);
								} else {
									unCanUseCoupons.push(coupon);
								}
							});
							this.setData({
								coupons: {
									totalLength: res.shopCartOrders[0].coupons.length,
									canUseCoupons: canUseCoupons,
									unCanUseCoupons: unCanUseCoupons
								}
							});
						}

						this.setData({
							orderItems: orderItems,
							actualTotal: res.actualTotal,
							total: res.total,
							totalCount: res.totalCount,
							userAddr: res.userAddr,
							transfee: res.shopCartOrders[0].transfee,
							shopReduce: res.shopCartOrders[0].shopReduce
						});
					},
					errCallBack: res => {
						uni.hideLoading();
						this.chooseCouponErrHandle(res);
					}
				};
				http.request(params);
			},

			/**
			 * 优惠券选择出错处理方法
			 */
			chooseCouponErrHandle(res) {
				// 优惠券不能共用处理方法
				if (res.statusCode == 601) {
					uni.showToast({
						title: res.data,
						icon: "none",
						duration: 3000,
						success: res => {
							this.setData({
								couponIds: []
							});
						}
					});
					setTimeout(() => {
						this.loadOrderData();
					}, 2500);
				}
			},

			/**
			 * 提交订单
			 */
			toPay: function() {
				// if (!this.userAddr) {
				// 	uni.showToast({
				// 		title: '请选择地址',
				// 		icon: "none"
				// 	});
				// 	return;
				// }
				uni.showModal({
					title: "友情提醒",
					content: '货物自提，请添加客服微信',
					success: (res) => {
						if (this.from == 'video') {
							this.submitOrder()
						} else {
							if (!this.hasPassword) {
								uni.showModal({
									content: '请先设置安全密码',
									confirmText: '去设置',
									success: (res) => {
										uni.navigateTo({
											url: '/package-task/pages/member/cash-password?from=mall'
										})
									},
								})
								return
							}
							this.$refs.popup.open('bottom')
						}
					},
				})

			},

			securityCodeConfirm() {
				console.log('安全密码：', this.securityCode);
				this.$refs.popup.close()
				this.submitOrder()
			},

			submitOrder: function() {
				uni.showLoading({
					mask: true
				});
				var params = {
					url: "/p/order/submit",
					method: "POST",
					data: {
						orderShopParam: [{
							remarks: this.remarks,
							shopId: 1
						}]
					},
					callBack: res => {
						console.log("res", res)
						uni.hideLoading();
						if (this.from == 'video') {
							//现金支付
							this.getOrderInfo(res.orderNumbers)
						} else {
							//余额支付
							this.calWeixinPay(res.orderNumbers);
						}
						// this.calWeixinPay(res.orderNumbers);
						// this.calWeixinPay(res);
						// this.wxinPay(res)
						// this.normalPay(res.orderNumbers)

					}
				};
				http.request(params);
			},

			//选择支付方式
			onCheck(index, payType) {
				this.currentIndex = index
				this.payType = payType
			},

			/**
			 * 获取订单信息
			 */
			getOrderInfo(orderNumbers) {
				let datas = {
					payType: this.payType,
					orderNumbers: orderNumbers,
					belongId: this.belongId,
					userId: this.userId
				}
				console.log('payAccount 请求参数：', datas)

				uni.showLoading({
					mask: true
				});
				var params = {
					url: "/p/order/pay",
					method: "POST",
					// data: {
					//   payType: 1,
					//   orderNumbers: orderNumbers
					// },
					data: datas,
					callBack: res => {
						console.log('订单结果：', res)
						if (this.payType == 1) {
							this.weixinPay(res, orderNumbers)
						} else {
							this.aliPay(res, orderNumbers)
						}
					}
				};
				http.request(params);
			},

			//微信支付
			weixinPay(orderInfo, orderNumbers) {
				console.log('微信支付订单信息：', orderInfo)
				// 微信支付
				uni.requestPayment({
					provider: "wxpay",
					orderInfo: orderInfo,
					success: (res) => {
						console.log("支付 res: ", res);
						uni.hideLoading();
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=1&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
					},
					fail: (err) => {
						console.log("支付 err: ", err);
						uni.hideLoading();
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=0&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
					}
				})
			},
			aliPay(orderInfo) {
				console.log('支付支付宝订单信息：', orderInfo)
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: orderInfo.body,
					success: (res) => {
						console.log("支付成功: ", res);
						uni.hideLoading();
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=1&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
					},
					fail: (err) => {
						console.log("支付 err: ", err);
						uni.hideLoading();
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=0&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
					}
				})
			},

			/**
			 * 余额支付
			 */
			calWeixinPay: function(orderNumbers) {
				let that = this
				let datas = {
					payType: 1,
					orderNumbers: orderNumbers,
					inviteeUserId: that.inviter,
					userId: that.userId,
					password: that.securityCode
				}
				console.log('payAccount 请求参数：', datas)

				uni.showLoading({
					mask: true
				});
				var params = {
					url: "/p/order/payAccount",
					method: "POST",
					data: datas,
					callBack: function(res) {
						console.log('订单结果：', res)

						if (res.code && res.code == "103") {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
							return false
						}
						// if(res.status==500){
						// 	console.log('500...')
						// 	uni.navigateTo({
						// 		url:'/package-mall/pages/submit-order/invitor'
						// 	})
						// 	return
						// }
						if (res.code && res.code == 'ERR102') {
							uni.showToast({
								// title:'请填写邀请人信息',
								title: '请填写实名认证信息',
								icon: 'none',
								duration: 2000
							})
							uni.navigateTo({
								// from2用于判断邀请人页面是否需要填手机号
								url: '/package-mall/pages/submit-order/invitor?from2=php'
							})
							return
						}
						if (res.code == "102") {
							uni.showToast({
								// title:'请填写邀请人',
								title: '请填写实名认证信息',
								icon: 'none',
								duration: 1500
							})
							uni.navigateTo({
								url: '/package-mall/pages/submit-order/invitor'
							})
							return
						}
						if (res.code && res.code == "000") {
							that.diskAddress = res.diskAddress
							that.diskCode = res.diskCode
							uni.navigateTo({
								url: '/package-mall/pages/pay-result/pay-result?sts=1&orderNumbers=' +
									orderNumbers + "&orderType=" + that.orderType + "&isMember=" + that
									.isMember +
									"&diskAddress=" + that.diskAddress + "&diskCode=" + that.diskCode
							});

						} else {
							uni.navigateTo({
								url: '/package-mall/pages/pay-result/pay-result?sts=0&orderNumbers=' +
									orderNumbers + "&orderType=" + that.orderType
							});
						}
						uni.hideLoading();
						return
						uni.requestPayment({
							provider: "wxpay",
							orderInfo: orderInfo,
							success: e => {
								console.log('吊起支付 res:', e);
								// console.log("支付成功");
								uni.navigateTo({
									url: '/package-mall/pages/pay-result/pay-result?sts=1&orderNumbers=' +
										orderNumbers + "&orderType=" + this.orderType
								});
							},
							fail: err => {
								console.log('吊起支付err:', err)
								uni.navigateTo({
									url: '/package-mall/pages/pay-result/pay-result?sts=0&orderNumbers=' +
										orderNumbers + "&orderType=" + this.orderType
								});
							}
						});
					}
				};
				http.request(params);
			},
			wxinPay(res) {
				console.log('wxPay...', res)
				var orderInfo = res;
				// 微信支付
				uni.requestPayment({
					provider: "wxpay",
					orderInfo: orderInfo,
					success: (res) => {
						console.log("支付 res: ", res);
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=1&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
						// setTimeout(this.getMyInfo(), 2000);
					},
					fail: (err) => {
						console.log("支付 err: ", err);
						uni.navigateTo({
							url: '/package-mall/pages/pay-result/pay-result?sts=0&orderNumbers=' +
								orderNumbers + "&orderType=" + this.orderType
						});
					}
				})
			},
			changeCouponSts: function(e) {
				this.setData({
					couponSts: e.currentTarget.dataset.sts
				});
			},
			showCouponPopup: function() {
				this.setData({
					popupShow: true
				});
			},
			closePopup: function() {
				this.setData({
					popupShow: false
				});
			},

			/**
			 * 去地址页面
			 */
			toAddrListPage: function() {
				uni.navigateTo({
					url: '/package-mall/pages/delivery-address/delivery-address?order=0'
				});
			},

			/**
			 * 确定选择好的优惠券
			 */
			choosedCoupon: function() {
				this.loadOrderData();
				this.setData({
					popupShow: false
				});
			},

			/**
			 * 优惠券子组件发过来
			 */
			checkCoupon: function(e) {
				var ths = this;
				let index = ths.couponIds.indexOf(e.detail.couponId);

				if (index === -1) {
					ths.couponIds.push(e.detail.couponId);
				} else {
					ths.couponIds.splice(index, 1);
				}
			}
		}
	};
</script>
<style>
	@import "./submit-order.css";
</style>
